package com.osgix.common.utils;

import java.io.Reader;
import java.io.StringReader;
import java.io.StringWriter;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

import org.apache.log4j.Logger;

/**
 * @author azheng
 */
public class XmlUtils {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(XmlUtils.class);

	/**
	 * Object 生成 XML String
	 * 
	 * @param obj
	 * @return String
	 * @throws JAXBException
	 */
	public static String generateXml(Object obj) throws JAXBException {
		JAXBContext context;
		StringWriter sw = new StringWriter();
		context = JAXBContext.newInstance("com.gm.gmcmarket.adp.model");
		Marshaller m = context.createMarshaller();
		// m.marshal(catalogElement,new FileOutputStream(xmlDocument));
		m.marshal(obj, sw);
		m.setProperty("jaxb.encoding", "utf-8");// 设置编码
		m.setProperty("jaxb.formatted.output", true);// 设置xml是否格式化
		String xmlStr = sw.getBuffer().toString();
		if (logger.isDebugEnabled()) {
			logger.debug(xmlStr);
		}
		return xmlStr;
	}

	/**
	 * 解析 XML String 为 Object
	 * 
	 * @param xmlStr
	 * @return Object
	 * @throws JAXBException
	 */
	public static Object parseXml(String xmlStr) throws JAXBException {
		JAXBContext jc = JAXBContext.newInstance("com.gm.gmcmarket.adp.model:com.gm.gmcmarket.adp.soapModel");
		Unmarshaller u = jc.createUnmarshaller();
		Reader sr = new StringReader(xmlStr);
		Object obj = u.unmarshal(sr);
		return obj;
	}
}
